﻿using Application.Interfaces.Repository;
using System.Collections.Generic;
using System.Data.Entity;

namespace Infrastructure.Implementations.Repository.EntityFramework
{
    public class EfRepositoryProvider : IRepositoryProvider
    {
        public EfRepositoryProvider(SeedPattern pattern, string connectionString)
        {
            this.Pattern = pattern;
            this.ConnectionString = connectionString;
        }

        public string ConnectionString { get; private set; }

        public SeedPattern Pattern { get; private set; }

        public List<object> Entities { get; private set; }

        public void Config(List<object> entities)
        {
            this.Entities = entities;

            if (Pattern == SeedPattern.DropCreateDatabaseAlways)
            {
                Database.SetInitializer<MyDbContext>(new DropCreateAlways(Entities));
            }
            else if (Pattern == SeedPattern.DropCreateDatabaseIfModelChanges)
            {
                Database.SetInitializer<MyDbContext>(new DropCreateIfModelChanges(Entities));
            }
            else
            {
                Database.SetInitializer<MyDbContext>(null);
            }
            using (var db = new MyDbContext(this))
            {
            }
        }

        private class DropCreateAlways : DropCreateDatabaseAlways<MyDbContext>
        {
            private List<object> _entities { get; set; }

            public DropCreateAlways(List<object> entities)
            {
                this._entities = entities;
            }

            protected override void Seed(MyDbContext context)
            {
                base.Seed(context);
                if (_entities != null)
                {
                    foreach (var item in _entities)
                    {
                        context.Set(item.GetType()).Add(item);
                    }
                }
            }
        }

        private class DropCreateIfModelChanges : DropCreateDatabaseIfModelChanges<MyDbContext>
        {
            private List<object> _entities { get; set; }

            public DropCreateIfModelChanges(List<object> entities)
            {
                this._entities = entities;
            }

            protected override void Seed(MyDbContext context)
            {
                base.Seed(context);
                if (_entities != null)
                {
                    foreach (var item in _entities)
                    {
                        context.Set(item.GetType()).Add(item);
                    }
                }
            }
        }
    }
}